package com.jjlin.mapper;

import com.jjlin.entity.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface BlogRepository extends JpaRepository<Blog, Long>, JpaSpecificationExecutor<Blog> {

    @Query("select b from Blog b where b.recommend = true and b.published = true")
    List<Blog> findTop(Pageable pageable);//查询发布同时推荐的博客

    @Query("select b from Blog b where b.published = true")
    List<Blog> findNewBlog(Pageable pageable);//查询发布的所有博客

    @Query("select b from Blog b where b.type.id = ?1 and b.published = true")
    Page<Blog> findByTypeId(Long id, Pageable pageable);//查询发布同时符合分类id的博客

    @Query("select b from Blog b where b.published = true and (b.title like ?1 or b.content like ?1 or b.description like ?1)")
    Page<Blog> findByQuery(String query, Pageable pageable);//查询发布且符合搜索字符串的博客

    @Query("select function('date_format',b.updateTime,'%Y') as year from Blog b where b.published = true group by function('date_format',b.updateTime,'%Y') order by function('date_format',b.updateTime,'%Y') desc")
    List<String> findGroupYear();//查询发布博客的所有更新时间年份

    @Query("select b from Blog b where function('date_format',b.updateTime,'%Y') = ?1 and b.published = true")
    List<Blog> findByYear(String year);//根据更新时间年份查询所有发布的博客

    @Query("select count(b) from Blog b where b.published = true")
    Long countByPublished();//查询所有发布博客的总数

    @Transactional
    @Modifying
    @Query("update Blog b set b.views = b.views+1 where b.id = ?1 and b.published = true")
    int updateViews(Long id);
}
